winemac: Simplify format_for_type() and callers since there's at most one format...
[wine.git] / dlls / msi / database.c
blob34f8d045336b4153e247b2dd53e49a32d86d1c9e
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
4 * Copyright 2002,2003,2004,2005 Mike McCormack for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include <stdarg.h>
22 #include <stdio.h>
24 #define COBJMACROS
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "wine/debug.h"
31 #include "wine/unicode.h"
32 #include "msi.h"
33 #include "msiquery.h"
34 #include "msipriv.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "msiserver.h"
38 #include "query.h"
40 #include "initguid.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(msi);
45 * .MSI file format
47 * An .msi file is a structured storage file.
48 * It contains a number of streams.
49 * A stream for each table in the database.
50 * Two streams for the string table in the database.
51 * Any binary data in a table is a reference to a stream.
54 #define IS_INTMSIDBOPEN(x) (((ULONG_PTR)(x) >> 16) == 0)
56 static void free_transforms( MSIDATABASE *db )
58 while( !list_empty( &db->transforms ) )
60 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ), MSITRANSFORM, entry );
61 list_remove( &t->entry );
62 IStorage_Release( t->stg );
63 msi_free( t );
67 static void free_streams( MSIDATABASE *db )
69 UINT i;
70 for (i = 0; i < db->num_streams; i++)
72 if (db->streams[i].stream) IStream_Release( db->streams[i].stream );
74 msi_free( db->streams );
77 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
79 MSITRANSFORM *t;
81 t = msi_alloc( sizeof *t );
82 t->stg = stg;
83 IStorage_AddRef( stg );
84 list_add_head( &db->transforms, &t->entry );
87 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
89 MSIDATABASE *db = (MSIDATABASE *) arg;
91 msi_free(db->path);
92 free_streams( db );
93 free_cached_tables( db );
94 free_transforms( db );
95 if (db->strings) msi_destroy_stringtable( db->strings );
96 IStorage_Release( db->storage );
97 if (db->deletefile)
99 DeleteFileW( db->deletefile );
100 msi_free( db->deletefile );
102 msi_free( db->tempfolder );
105 static HRESULT db_initialize( IStorage *stg, const GUID *clsid )
107 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
108 HRESULT hr;
110 hr = IStorage_SetClass( stg, clsid );
111 if (FAILED( hr ))
113 WARN("failed to set class id 0x%08x\n", hr);
114 return hr;
117 /* create the _Tables stream */
118 hr = write_stream_data( stg, szTables, NULL, 0, TRUE );
119 if (FAILED( hr ))
121 WARN("failed to create _Tables stream 0x%08x\n", hr);
122 return hr;
125 hr = msi_init_string_table( stg );
126 if (FAILED( hr ))
128 WARN("failed to initialize string table 0x%08x\n", hr);
129 return hr;
132 hr = IStorage_Commit( stg, 0 );
133 if (FAILED( hr ))
135 WARN("failed to commit changes 0x%08x\n", hr);
136 return hr;
139 return S_OK;
142 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
144 IStorage *stg = NULL;
145 HRESULT r;
146 MSIDATABASE *db = NULL;
147 UINT ret = ERROR_FUNCTION_FAILED;
148 LPCWSTR szMode, save_path;
149 STATSTG stat;
150 BOOL created = FALSE, patch = FALSE;
151 WCHAR path[MAX_PATH];
153 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
155 if( !pdb )
156 return ERROR_INVALID_PARAMETER;
158 if (szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
160 TRACE("Database is a patch\n");
161 szPersist -= MSIDBOPEN_PATCHFILE;
162 patch = TRUE;
165 save_path = szDBPath;
166 szMode = szPersist;
167 if( !IS_INTMSIDBOPEN(szPersist) )
169 if (!CopyFileW( szDBPath, szPersist, FALSE ))
170 return ERROR_OPEN_FAILED;
172 szDBPath = szPersist;
173 szPersist = MSIDBOPEN_TRANSACT;
174 created = TRUE;
177 if( szPersist == MSIDBOPEN_READONLY )
179 r = StgOpenStorage( szDBPath, NULL,
180 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
182 else if( szPersist == MSIDBOPEN_CREATE )
184 r = StgCreateDocfile( szDBPath,
185 STGM_CREATE|STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
187 if( SUCCEEDED(r) )
188 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
189 created = TRUE;
191 else if( szPersist == MSIDBOPEN_CREATEDIRECT )
193 r = StgCreateDocfile( szDBPath,
194 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
196 if( SUCCEEDED(r) )
197 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
198 created = TRUE;
200 else if( szPersist == MSIDBOPEN_TRANSACT )
202 r = StgOpenStorage( szDBPath, NULL,
203 STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
205 else if( szPersist == MSIDBOPEN_DIRECT )
207 r = StgOpenStorage( szDBPath, NULL,
208 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
210 else
212 ERR("unknown flag %p\n",szPersist);
213 return ERROR_INVALID_PARAMETER;
216 if( FAILED( r ) || !stg )
218 WARN("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
219 return ERROR_FUNCTION_FAILED;
222 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
223 if( FAILED( r ) )
225 FIXME("Failed to stat storage\n");
226 goto end;
229 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
230 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
231 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
233 ERR("storage GUID is not a MSI database GUID %s\n",
234 debugstr_guid(&stat.clsid) );
235 goto end;
238 if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
240 ERR("storage GUID is not the MSI patch GUID %s\n",
241 debugstr_guid(&stat.clsid) );
242 ret = ERROR_OPEN_FAILED;
243 goto end;
246 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
247 MSI_CloseDatabase );
248 if( !db )
250 FIXME("Failed to allocate a handle\n");
251 goto end;
254 if (!strchrW( save_path, '\\' ))
256 GetCurrentDirectoryW( MAX_PATH, path );
257 lstrcatW( path, szBackSlash );
258 lstrcatW( path, save_path );
260 else
261 lstrcpyW( path, save_path );
263 db->path = strdupW( path );
264 db->media_transform_offset = MSI_INITIAL_MEDIA_TRANSFORM_OFFSET;
265 db->media_transform_disk_id = MSI_INITIAL_MEDIA_TRANSFORM_DISKID;
267 if( TRACE_ON( msi ) )
268 enum_stream_names( stg );
270 db->storage = stg;
271 db->mode = szMode;
272 if (created)
273 db->deletefile = strdupW( szDBPath );
274 list_init( &db->tables );
275 list_init( &db->transforms );
277 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
278 if( !db->strings )
279 goto end;
281 ret = ERROR_SUCCESS;
283 msiobj_addref( &db->hdr );
284 IStorage_AddRef( stg );
285 *pdb = db;
287 end:
288 if( db )
289 msiobj_release( &db->hdr );
290 if( stg )
291 IStorage_Release( stg );
293 return ret;
296 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
298 MSIDATABASE *db;
299 UINT ret;
301 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
303 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
304 if( ret == ERROR_SUCCESS )
306 *phDB = alloc_msihandle( &db->hdr );
307 if (! *phDB)
308 ret = ERROR_NOT_ENOUGH_MEMORY;
309 msiobj_release( &db->hdr );
312 return ret;
315 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
317 HRESULT r = ERROR_FUNCTION_FAILED;
318 LPWSTR szwDBPath = NULL, szwPersist = NULL;
320 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
322 if( szDBPath )
324 szwDBPath = strdupAtoW( szDBPath );
325 if( !szwDBPath )
326 goto end;
329 if( !IS_INTMSIDBOPEN(szPersist) )
331 szwPersist = strdupAtoW( szPersist );
332 if( !szwPersist )
333 goto end;
335 else
336 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
338 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
340 end:
341 if( !IS_INTMSIDBOPEN(szPersist) )
342 msi_free( szwPersist );
343 msi_free( szwDBPath );
345 return r;
348 static LPWSTR msi_read_text_archive(LPCWSTR path, DWORD *len)
350 HANDLE file;
351 LPSTR data = NULL;
352 LPWSTR wdata = NULL;
353 DWORD read, size = 0;
355 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
356 if (file == INVALID_HANDLE_VALUE)
357 return NULL;
359 size = GetFileSize( file, NULL );
360 if (!(data = msi_alloc( size ))) goto done;
362 if (!ReadFile( file, data, size, &read, NULL ) || read != size) goto done;
364 while (!data[size - 1]) size--;
365 *len = MultiByteToWideChar( CP_ACP, 0, data, size, NULL, 0 );
366 if ((wdata = msi_alloc( (*len + 1) * sizeof(WCHAR) )))
368 MultiByteToWideChar( CP_ACP, 0, data, size, wdata, *len );
369 wdata[*len] = 0;
372 done:
373 CloseHandle( file );
374 msi_free( data );
375 return wdata;
378 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries, DWORD *len)
380 LPWSTR ptr = *line, save;
381 DWORD i, count = 1, chars_left = *len;
383 *entries = NULL;
385 /* stay on this line */
386 while (chars_left && *ptr != '\n')
388 /* entries are separated by tabs */
389 if (*ptr == '\t')
390 count++;
392 ptr++;
393 chars_left--;
396 *entries = msi_alloc(count * sizeof(LPWSTR));
397 if (!*entries)
398 return;
400 /* store pointers into the data */
401 chars_left = *len;
402 for (i = 0, ptr = *line; i < count; i++)
404 while (chars_left && *ptr == '\r')
406 ptr++;
407 chars_left--;
409 save = ptr;
411 while (chars_left && *ptr != '\t' && *ptr != '\n' && *ptr != '\r')
413 if (!*ptr) *ptr = '\n'; /* convert embedded nulls to \n */
414 if (ptr > *line && *ptr == '\x19' && *(ptr - 1) == '\x11')
416 *ptr = '\n';
417 *(ptr - 1) = '\r';
419 ptr++;
420 chars_left--;
423 /* NULL-separate the data */
424 if (*ptr == '\n' || *ptr == '\r')
426 while (chars_left && (*ptr == '\n' || *ptr == '\r'))
428 *(ptr++) = 0;
429 chars_left--;
432 else if (*ptr)
434 *(ptr++) = 0;
435 chars_left--;
437 (*entries)[i] = save;
440 /* move to the next line if there's more, else EOF */
441 *line = ptr;
442 *len = chars_left;
443 if (num_entries)
444 *num_entries = count;
447 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
449 LPWSTR prelude;
450 DWORD size;
452 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
454 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
455 prelude = msi_alloc(size * sizeof(WCHAR));
456 if (!prelude)
457 return NULL;
459 sprintfW(prelude, create_fmt, table);
460 return prelude;
463 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
465 LPWSTR columns, p;
466 LPCWSTR type;
467 DWORD sql_size = 1, i, len;
468 WCHAR expanded[128], *ptr;
469 WCHAR size[10], comma[2], extra[30];
471 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
472 static const WCHAR size_fmt[] = {'(','%','s',')',0};
473 static const WCHAR type_char[] = {'C','H','A','R',0};
474 static const WCHAR type_int[] = {'I','N','T',0};
475 static const WCHAR type_long[] = {'L','O','N','G',0};
476 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
477 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
478 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
480 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
481 if (!columns)
482 return NULL;
484 for (i = 0; i < num_columns; i++)
486 type = NULL;
487 comma[1] = size[0] = extra[0] = '\0';
489 if (i == num_columns - 1)
490 comma[0] = '\0';
491 else
492 comma[0] = ',';
494 ptr = &types[i][1];
495 len = atolW(ptr);
496 extra[0] = '\0';
498 switch (types[i][0])
500 case 'l':
501 lstrcpyW(extra, type_notnull);
502 /* fall through */
503 case 'L':
504 lstrcatW(extra, localizable);
505 type = type_char;
506 sprintfW(size, size_fmt, ptr);
507 break;
508 case 's':
509 lstrcpyW(extra, type_notnull);
510 /* fall through */
511 case 'S':
512 type = type_char;
513 sprintfW(size, size_fmt, ptr);
514 break;
515 case 'i':
516 lstrcpyW(extra, type_notnull);
517 /* fall through */
518 case 'I':
519 if (len <= 2)
520 type = type_int;
521 else if (len == 4)
522 type = type_long;
523 else
525 WARN("invalid int width %u\n", len);
526 msi_free(columns);
527 return NULL;
529 break;
530 case 'v':
531 lstrcpyW(extra, type_notnull);
532 /* fall through */
533 case 'V':
534 type = type_object;
535 break;
536 default:
537 ERR("Unknown type: %c\n", types[i][0]);
538 msi_free(columns);
539 return NULL;
542 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
543 sql_size += lstrlenW(expanded);
545 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
546 if (!p)
548 msi_free(columns);
549 return NULL;
551 columns = p;
553 lstrcatW(columns, expanded);
556 return columns;
559 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
561 LPWSTR postlude, keys, ptr;
562 DWORD size, i;
564 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
565 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
567 for (i = 0, size = 1; i < num_keys; i++)
568 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
570 keys = msi_alloc(size * sizeof(WCHAR));
571 if (!keys)
572 return NULL;
574 for (i = 0, ptr = keys; i < num_keys; i++)
576 ptr += sprintfW(ptr, key_fmt, primary_keys[i]);
579 /* remove final ', ' */
580 *(ptr - 2) = '\0';
582 size = lstrlenW(postlude_fmt) + size - 1;
583 postlude = msi_alloc(size * sizeof(WCHAR));
584 if (!postlude)
585 goto done;
587 sprintfW(postlude, postlude_fmt, keys);
589 done:
590 msi_free(keys);
591 return postlude;
594 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
596 UINT r = ERROR_OUTOFMEMORY;
597 DWORD size;
598 MSIQUERY *view;
599 LPWSTR create_sql = NULL;
600 LPWSTR prelude, columns_sql, postlude;
602 prelude = msi_build_createsql_prelude(labels[0]);
603 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
604 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
606 if (!prelude || !columns_sql || !postlude)
607 goto done;
609 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
610 create_sql = msi_alloc(size * sizeof(WCHAR));
611 if (!create_sql)
612 goto done;
614 lstrcpyW(create_sql, prelude);
615 lstrcatW(create_sql, columns_sql);
616 lstrcatW(create_sql, postlude);
618 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
619 if (r != ERROR_SUCCESS)
620 goto done;
622 r = MSI_ViewExecute(view, NULL);
623 MSI_ViewClose(view);
624 msiobj_release(&view->hdr);
626 done:
627 msi_free(prelude);
628 msi_free(columns_sql);
629 msi_free(postlude);
630 msi_free(create_sql);
631 return r;
634 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
636 DWORD len;
637 LPWSTR fullname, ptr;
639 len = lstrlenW(path) + lstrlenW(name) + 1;
640 fullname = msi_alloc(len*sizeof(WCHAR));
641 if (!fullname)
642 return NULL;
644 lstrcpyW( fullname, path );
646 /* chop off extension from path */
647 ptr = strrchrW(fullname, '.');
648 if (!ptr)
650 msi_free (fullname);
651 return NULL;
653 *ptr++ = '\\';
654 lstrcpyW( ptr, name );
655 return fullname;
658 static UINT construct_record(DWORD num_columns, LPWSTR *types,
659 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
661 UINT i;
663 *rec = MSI_CreateRecord(num_columns);
664 if (!*rec)
665 return ERROR_OUTOFMEMORY;
667 for (i = 0; i < num_columns; i++)
669 switch (types[i][0])
671 case 'L': case 'l': case 'S': case 's':
672 MSI_RecordSetStringW(*rec, i + 1, data[i]);
673 break;
674 case 'I': case 'i':
675 if (*data[i])
676 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
677 break;
678 case 'V': case 'v':
679 if (*data[i])
681 UINT r;
682 LPWSTR file = msi_import_stream_filename(path, data[i]);
683 if (!file)
684 return ERROR_FUNCTION_FAILED;
686 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
687 msi_free (file);
688 if (r != ERROR_SUCCESS)
689 return ERROR_FUNCTION_FAILED;
691 break;
692 default:
693 ERR("Unhandled column type: %c\n", types[i][0]);
694 msiobj_release(&(*rec)->hdr);
695 return ERROR_FUNCTION_FAILED;
699 return ERROR_SUCCESS;
702 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
703 LPWSTR *labels, LPWSTR **records,
704 int num_columns, int num_records,
705 LPWSTR path)
707 UINT r;
708 int i;
709 MSIQUERY *view;
710 MSIRECORD *rec;
712 static const WCHAR select[] = {
713 'S','E','L','E','C','T',' ','*',' ',
714 'F','R','O','M',' ','`','%','s','`',0
717 r = MSI_OpenQuery(db, &view, select, labels[0]);
718 if (r != ERROR_SUCCESS)
719 return r;
721 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
723 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
724 msiobj_release(&rec->hdr);
725 if (r != ERROR_SUCCESS)
726 goto done;
729 for (i = 0; i < num_records; i++)
731 r = construct_record(num_columns, types, records[i], path, &rec);
732 if (r != ERROR_SUCCESS)
733 goto done;
735 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
736 if (r != ERROR_SUCCESS)
738 msiobj_release(&rec->hdr);
739 goto done;
742 msiobj_release(&rec->hdr);
745 done:
746 msiobj_release(&view->hdr);
747 return r;
750 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
752 UINT r;
753 DWORD len, i;
754 DWORD num_labels, num_types;
755 DWORD num_columns, num_records = 0;
756 LPWSTR *columns, *types, *labels;
757 LPWSTR path, ptr, data;
758 LPWSTR **records = NULL;
759 LPWSTR **temp_records;
761 static const WCHAR suminfo[] =
762 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
763 static const WCHAR forcecodepage[] =
764 {'_','F','o','r','c','e','C','o','d','e','p','a','g','e',0};
766 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
768 if( folder == NULL || file == NULL )
769 return ERROR_INVALID_PARAMETER;
771 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
772 path = msi_alloc( len * sizeof(WCHAR) );
773 if (!path)
774 return ERROR_OUTOFMEMORY;
776 lstrcpyW( path, folder );
777 lstrcatW( path, szBackSlash );
778 lstrcatW( path, file );
780 data = msi_read_text_archive( path, &len );
782 ptr = data;
783 msi_parse_line( &ptr, &columns, &num_columns, &len );
784 msi_parse_line( &ptr, &types, &num_types, &len );
785 msi_parse_line( &ptr, &labels, &num_labels, &len );
787 if (num_columns == 1 && !columns[0][0] && num_labels == 1 && !labels[0][0] &&
788 num_types == 2 && !strcmpW( types[1], forcecodepage ))
790 r = msi_set_string_table_codepage( db->strings, atoiW( types[0] ) );
791 goto done;
794 if (num_columns != num_types)
796 r = ERROR_FUNCTION_FAILED;
797 goto done;
800 records = msi_alloc(sizeof(LPWSTR *));
801 if (!records)
803 r = ERROR_OUTOFMEMORY;
804 goto done;
807 /* read in the table records */
808 while (len)
810 msi_parse_line( &ptr, &records[num_records], NULL, &len );
812 num_records++;
813 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
814 if (!temp_records)
816 r = ERROR_OUTOFMEMORY;
817 goto done;
819 records = temp_records;
822 if (!strcmpW(labels[0], suminfo))
824 r = msi_add_suminfo( db, records, num_records, num_columns );
825 if (r != ERROR_SUCCESS)
827 r = ERROR_FUNCTION_FAILED;
828 goto done;
831 else
833 if (!TABLE_Exists(db, labels[0]))
835 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
836 if (r != ERROR_SUCCESS)
838 r = ERROR_FUNCTION_FAILED;
839 goto done;
843 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
846 done:
847 msi_free(path);
848 msi_free(data);
849 msi_free(columns);
850 msi_free(types);
851 msi_free(labels);
853 for (i = 0; i < num_records; i++)
854 msi_free(records[i]);
856 msi_free(records);
858 return r;
861 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
863 MSIDATABASE *db;
864 UINT r;
866 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
868 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
869 if( !db )
871 IWineMsiRemoteDatabase *remote_database;
873 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
874 if ( !remote_database )
875 return ERROR_INVALID_HANDLE;
877 IWineMsiRemoteDatabase_Release( remote_database );
878 WARN("MsiDatabaseImport not allowed during a custom action!\n");
880 return ERROR_SUCCESS;
883 r = MSI_DatabaseImport( db, szFolder, szFilename );
884 msiobj_release( &db->hdr );
885 return r;
888 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
889 LPCSTR szFolder, LPCSTR szFilename )
891 LPWSTR path = NULL, file = NULL;
892 UINT r = ERROR_OUTOFMEMORY;
894 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
896 if( szFolder )
898 path = strdupAtoW( szFolder );
899 if( !path )
900 goto end;
903 if( szFilename )
905 file = strdupAtoW( szFilename );
906 if( !file )
907 goto end;
910 r = MsiDatabaseImportW( handle, path, file );
912 end:
913 msi_free( path );
914 msi_free( file );
916 return r;
919 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
921 UINT i, count, len, r = ERROR_SUCCESS;
922 const char *sep;
923 char *buffer;
924 DWORD sz;
926 len = 0x100;
927 buffer = msi_alloc( len );
928 if ( !buffer )
929 return ERROR_OUTOFMEMORY;
931 count = MSI_RecordGetFieldCount( row );
932 for ( i=start; i<=count; i++ )
934 sz = len;
935 r = MSI_RecordGetStringA( row, i, buffer, &sz );
936 if (r == ERROR_MORE_DATA)
938 char *p = msi_realloc( buffer, sz + 1 );
939 if (!p)
940 break;
941 len = sz + 1;
942 buffer = p;
944 sz = len;
945 r = MSI_RecordGetStringA( row, i, buffer, &sz );
946 if (r != ERROR_SUCCESS)
947 break;
949 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
951 r = ERROR_FUNCTION_FAILED;
952 break;
955 sep = (i < count) ? "\t" : "\r\n";
956 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
958 r = ERROR_FUNCTION_FAILED;
959 break;
962 msi_free( buffer );
963 return r;
966 static UINT msi_export_row( MSIRECORD *row, void *arg )
968 return msi_export_record( arg, row, 1 );
971 static UINT msi_export_forcecodepage( HANDLE handle, UINT codepage )
973 static const char fmt[] = "\r\n\r\n%u\t_ForceCodepage\r\n";
974 char data[sizeof(fmt) + 10];
975 DWORD sz;
977 sprintf( data, fmt, codepage );
979 sz = lstrlenA(data) + 1;
980 if (!WriteFile(handle, data, sz, &sz, NULL))
981 return ERROR_FUNCTION_FAILED;
983 return ERROR_SUCCESS;
986 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
987 LPCWSTR folder, LPCWSTR file )
989 static const WCHAR query[] = {
990 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
991 static const WCHAR forcecodepage[] = {
992 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
993 MSIRECORD *rec = NULL;
994 MSIQUERY *view = NULL;
995 LPWSTR filename;
996 HANDLE handle;
997 UINT len, r;
999 TRACE("%p %s %s %s\n", db, debugstr_w(table),
1000 debugstr_w(folder), debugstr_w(file) );
1002 if( folder == NULL || file == NULL )
1003 return ERROR_INVALID_PARAMETER;
1005 len = lstrlenW(folder) + lstrlenW(file) + 2;
1006 filename = msi_alloc(len * sizeof (WCHAR));
1007 if (!filename)
1008 return ERROR_OUTOFMEMORY;
1010 lstrcpyW( filename, folder );
1011 lstrcatW( filename, szBackSlash );
1012 lstrcatW( filename, file );
1014 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1015 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1016 msi_free( filename );
1017 if (handle == INVALID_HANDLE_VALUE)
1018 return ERROR_FUNCTION_FAILED;
1020 if (!strcmpW( table, forcecodepage ))
1022 UINT codepage = msi_get_string_table_codepage( db->strings );
1023 r = msi_export_forcecodepage( handle, codepage );
1024 goto done;
1027 r = MSI_OpenQuery( db, &view, query, table );
1028 if (r == ERROR_SUCCESS)
1030 /* write out row 1, the column names */
1031 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1032 if (r == ERROR_SUCCESS)
1034 msi_export_record( handle, rec, 1 );
1035 msiobj_release( &rec->hdr );
1038 /* write out row 2, the column types */
1039 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1040 if (r == ERROR_SUCCESS)
1042 msi_export_record( handle, rec, 1 );
1043 msiobj_release( &rec->hdr );
1046 /* write out row 3, the table name + keys */
1047 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1048 if (r == ERROR_SUCCESS)
1050 MSI_RecordSetStringW( rec, 0, table );
1051 msi_export_record( handle, rec, 0 );
1052 msiobj_release( &rec->hdr );
1055 /* write out row 4 onwards, the data */
1056 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
1057 msiobj_release( &view->hdr );
1060 done:
1061 CloseHandle( handle );
1062 return r;
1065 /***********************************************************************
1066 * MsiExportDatabaseW [MSI.@]
1068 * Writes a file containing the table data as tab separated ASCII.
1070 * The format is as follows:
1072 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1073 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1074 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1076 * Followed by the data, starting at row 1 with one row per line
1078 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1080 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1081 LPCWSTR szFolder, LPCWSTR szFilename )
1083 MSIDATABASE *db;
1084 UINT r;
1086 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1087 debugstr_w(szFolder), debugstr_w(szFilename));
1089 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1090 if( !db )
1092 IWineMsiRemoteDatabase *remote_database;
1094 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1095 if ( !remote_database )
1096 return ERROR_INVALID_HANDLE;
1098 IWineMsiRemoteDatabase_Release( remote_database );
1099 WARN("MsiDatabaseExport not allowed during a custom action!\n");
1101 return ERROR_SUCCESS;
1104 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1105 msiobj_release( &db->hdr );
1106 return r;
1109 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1110 LPCSTR szFolder, LPCSTR szFilename )
1112 LPWSTR path = NULL, file = NULL, table = NULL;
1113 UINT r = ERROR_OUTOFMEMORY;
1115 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1116 debugstr_a(szFolder), debugstr_a(szFilename));
1118 if( szTable )
1120 table = strdupAtoW( szTable );
1121 if( !table )
1122 goto end;
1125 if( szFolder )
1127 path = strdupAtoW( szFolder );
1128 if( !path )
1129 goto end;
1132 if( szFilename )
1134 file = strdupAtoW( szFilename );
1135 if( !file )
1136 goto end;
1139 r = MsiDatabaseExportW( handle, table, path, file );
1141 end:
1142 msi_free( table );
1143 msi_free( path );
1144 msi_free( file );
1146 return r;
1149 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1150 LPCSTR szTableName)
1152 UINT r;
1153 LPWSTR table;
1155 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1156 debugstr_a(szTableName));
1158 table = strdupAtoW(szTableName);
1159 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1161 msi_free(table);
1162 return r;
1165 typedef struct _tagMERGETABLE
1167 struct list entry;
1168 struct list rows;
1169 LPWSTR name;
1170 DWORD numconflicts;
1171 LPWSTR *columns;
1172 DWORD numcolumns;
1173 LPWSTR *types;
1174 DWORD numtypes;
1175 LPWSTR *labels;
1176 DWORD numlabels;
1177 } MERGETABLE;
1179 typedef struct _tagMERGEROW
1181 struct list entry;
1182 MSIRECORD *data;
1183 } MERGEROW;
1185 typedef struct _tagMERGEDATA
1187 MSIDATABASE *db;
1188 MSIDATABASE *merge;
1189 MERGETABLE *curtable;
1190 MSIQUERY *curview;
1191 struct list *tabledata;
1192 } MERGEDATA;
1194 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1196 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1197 ((type2[0] == 'l') || (type2[0] == 's')))
1198 return TRUE;
1200 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1201 ((type2[0] == 'L') || (type2[0] == 'S')))
1202 return TRUE;
1204 return !strcmpW( type1, type2 );
1207 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1209 MSIRECORD *dbrec, *mergerec;
1210 UINT r, i, count;
1212 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1213 if (r != ERROR_SUCCESS)
1214 return r;
1216 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1217 if (r != ERROR_SUCCESS)
1219 msiobj_release(&dbrec->hdr);
1220 return r;
1223 count = MSI_RecordGetFieldCount(dbrec);
1224 for (i = 1; i <= count; i++)
1226 if (!MSI_RecordGetString(mergerec, i))
1227 break;
1229 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1231 r = ERROR_DATATYPE_MISMATCH;
1232 goto done;
1236 msiobj_release(&dbrec->hdr);
1237 msiobj_release(&mergerec->hdr);
1238 dbrec = mergerec = NULL;
1240 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1241 if (r != ERROR_SUCCESS)
1242 return r;
1244 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1245 if (r != ERROR_SUCCESS)
1247 msiobj_release(&dbrec->hdr);
1248 return r;
1251 count = MSI_RecordGetFieldCount(dbrec);
1252 for (i = 1; i <= count; i++)
1254 if (!MSI_RecordGetString(mergerec, i))
1255 break;
1257 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1258 MSI_RecordGetString(mergerec, i)))
1260 r = ERROR_DATATYPE_MISMATCH;
1261 break;
1265 done:
1266 msiobj_release(&dbrec->hdr);
1267 msiobj_release(&mergerec->hdr);
1269 return r;
1272 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1273 LPCWSTR table)
1275 MSIRECORD *dbrec, *mergerec = NULL;
1276 UINT r, i, count;
1278 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1279 if (r != ERROR_SUCCESS)
1280 return r;
1282 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1283 if (r != ERROR_SUCCESS)
1284 goto done;
1286 count = MSI_RecordGetFieldCount(dbrec);
1287 if (count != MSI_RecordGetFieldCount(mergerec))
1289 r = ERROR_DATATYPE_MISMATCH;
1290 goto done;
1293 for (i = 1; i <= count; i++)
1295 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1297 r = ERROR_DATATYPE_MISMATCH;
1298 goto done;
1302 done:
1303 msiobj_release(&dbrec->hdr);
1304 msiobj_release(&mergerec->hdr);
1306 return r;
1309 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1311 MSIRECORD *colnames;
1312 LPWSTR str, val;
1313 UINT r, i = 0, sz = 0;
1314 int cmp;
1316 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1317 if (r != ERROR_SUCCESS)
1318 return NULL;
1322 str = msi_dup_record_field(colnames, ++i);
1323 cmp = strcmpW( key, str );
1324 msi_free(str);
1325 } while (cmp);
1327 msiobj_release(&colnames->hdr);
1329 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1330 if (r != ERROR_SUCCESS)
1331 return NULL;
1332 sz++;
1334 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1336 /* quote string record fields */
1337 const WCHAR szQuote[] = {'\'', 0};
1338 sz += 2;
1339 val = msi_alloc(sz*sizeof(WCHAR));
1340 if (!val)
1341 return NULL;
1343 lstrcpyW(val, szQuote);
1344 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1345 lstrcpyW(val+1+sz, szQuote);
1347 else
1349 /* do not quote integer record fields */
1350 val = msi_alloc(sz*sizeof(WCHAR));
1351 if (!val)
1352 return NULL;
1354 r = MSI_RecordGetStringW(rec, i, val, &sz);
1357 if (r != ERROR_SUCCESS)
1359 ERR("failed to get string!\n");
1360 msi_free(val);
1361 return NULL;
1364 return val;
1367 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1368 LPWSTR table, MSIRECORD *rec)
1370 LPWSTR query = NULL, clause = NULL, val;
1371 LPCWSTR setptr, key;
1372 DWORD size, oldsize;
1373 MSIRECORD *keys;
1374 UINT r, i, count;
1376 static const WCHAR keyset[] = {
1377 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1378 static const WCHAR lastkeyset[] = {
1379 '`','%','s','`',' ','=',' ','%','s',' ',0};
1380 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1381 'F','R','O','M',' ','`','%','s','`',' ',
1382 'W','H','E','R','E',' ','%','s',0};
1384 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1385 if (r != ERROR_SUCCESS)
1386 return NULL;
1388 clause = msi_alloc_zero(sizeof(WCHAR));
1389 if (!clause)
1390 goto done;
1392 size = 1;
1393 count = MSI_RecordGetFieldCount(keys);
1394 for (i = 1; i <= count; i++)
1396 key = MSI_RecordGetString(keys, i);
1397 val = get_key_value(view, key, rec);
1399 if (i == count)
1400 setptr = lastkeyset;
1401 else
1402 setptr = keyset;
1404 oldsize = size;
1405 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1406 clause = msi_realloc(clause, size * sizeof (WCHAR));
1407 if (!clause)
1409 msi_free(val);
1410 goto done;
1413 sprintfW(clause + oldsize - 1, setptr, key, val);
1414 msi_free(val);
1417 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1418 query = msi_alloc(size * sizeof(WCHAR));
1419 if (!query)
1420 goto done;
1422 sprintfW(query, fmt, table, clause);
1424 done:
1425 msi_free(clause);
1426 msiobj_release(&keys->hdr);
1427 return query;
1430 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1432 MERGEDATA *data = param;
1433 MERGETABLE *table = data->curtable;
1434 MERGEROW *mergerow;
1435 MSIQUERY *dbview = NULL;
1436 MSIRECORD *row = NULL;
1437 LPWSTR query = NULL;
1438 UINT r = ERROR_SUCCESS;
1440 if (TABLE_Exists(data->db, table->name))
1442 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1443 if (!query)
1444 return ERROR_OUTOFMEMORY;
1446 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1447 if (r != ERROR_SUCCESS)
1448 goto done;
1450 r = MSI_ViewExecute(dbview, NULL);
1451 if (r != ERROR_SUCCESS)
1452 goto done;
1454 r = MSI_ViewFetch(dbview, &row);
1455 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1457 table->numconflicts++;
1458 goto done;
1460 else if (r != ERROR_NO_MORE_ITEMS)
1461 goto done;
1463 r = ERROR_SUCCESS;
1466 mergerow = msi_alloc(sizeof(MERGEROW));
1467 if (!mergerow)
1469 r = ERROR_OUTOFMEMORY;
1470 goto done;
1473 mergerow->data = MSI_CloneRecord(rec);
1474 if (!mergerow->data)
1476 r = ERROR_OUTOFMEMORY;
1477 msi_free(mergerow);
1478 goto done;
1481 list_add_tail(&table->rows, &mergerow->entry);
1483 done:
1484 msi_free(query);
1485 msiobj_release(&row->hdr);
1486 msiobj_release(&dbview->hdr);
1487 return r;
1490 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1492 UINT r, i, count;
1493 MSIRECORD *prec = NULL;
1495 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1496 if (r != ERROR_SUCCESS)
1497 return r;
1499 count = MSI_RecordGetFieldCount(prec);
1500 *numlabels = count + 1;
1501 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1502 if (!*labels)
1504 r = ERROR_OUTOFMEMORY;
1505 goto end;
1508 (*labels)[0] = strdupW(table);
1509 for (i=1; i<=count; i++ )
1511 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1514 end:
1515 msiobj_release( &prec->hdr );
1516 return r;
1519 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1521 UINT r, i, count;
1522 MSIRECORD *prec = NULL;
1524 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1525 if (r != ERROR_SUCCESS)
1526 return r;
1528 count = MSI_RecordGetFieldCount(prec);
1529 *columns = msi_alloc(count*sizeof(LPWSTR));
1530 if (!*columns)
1532 r = ERROR_OUTOFMEMORY;
1533 goto end;
1536 for (i=1; i<=count; i++ )
1538 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1541 *numcolumns = count;
1543 end:
1544 msiobj_release( &prec->hdr );
1545 return r;
1548 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1550 UINT r, i, count;
1551 MSIRECORD *prec = NULL;
1553 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1554 if (r != ERROR_SUCCESS)
1555 return r;
1557 count = MSI_RecordGetFieldCount(prec);
1558 *types = msi_alloc(count*sizeof(LPWSTR));
1559 if (!*types)
1561 r = ERROR_OUTOFMEMORY;
1562 goto end;
1565 *numtypes = count;
1566 for (i=1; i<=count; i++ )
1568 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1571 end:
1572 msiobj_release( &prec->hdr );
1573 return r;
1576 static void merge_free_rows(MERGETABLE *table)
1578 struct list *item, *cursor;
1580 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1582 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1584 list_remove(&row->entry);
1585 msiobj_release(&row->data->hdr);
1586 msi_free(row);
1590 static void free_merge_table(MERGETABLE *table)
1592 UINT i;
1594 if (table->labels != NULL)
1596 for (i = 0; i < table->numlabels; i++)
1597 msi_free(table->labels[i]);
1599 msi_free(table->labels);
1602 if (table->columns != NULL)
1604 for (i = 0; i < table->numcolumns; i++)
1605 msi_free(table->columns[i]);
1607 msi_free(table->columns);
1610 if (table->types != NULL)
1612 for (i = 0; i < table->numtypes; i++)
1613 msi_free(table->types[i]);
1615 msi_free(table->types);
1618 msi_free(table->name);
1619 merge_free_rows(table);
1621 msi_free(table);
1624 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1626 UINT r;
1627 MERGETABLE *table;
1628 MSIQUERY *mergeview = NULL;
1630 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1631 'F','R','O','M',' ','`','%','s','`',0};
1633 table = msi_alloc_zero(sizeof(MERGETABLE));
1634 if (!table)
1636 *ptable = NULL;
1637 return ERROR_OUTOFMEMORY;
1640 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1641 if (r != ERROR_SUCCESS)
1642 goto err;
1644 r = MSI_OpenQuery(db, &mergeview, query, name);
1645 if (r != ERROR_SUCCESS)
1646 goto err;
1648 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1649 if (r != ERROR_SUCCESS)
1650 goto err;
1652 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1653 if (r != ERROR_SUCCESS)
1654 goto err;
1656 list_init(&table->rows);
1658 table->name = strdupW(name);
1659 table->numconflicts = 0;
1661 msiobj_release(&mergeview->hdr);
1662 *ptable = table;
1663 return ERROR_SUCCESS;
1665 err:
1666 msiobj_release(&mergeview->hdr);
1667 free_merge_table(table);
1668 *ptable = NULL;
1669 return r;
1672 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1674 MERGEDATA *data = param;
1675 MERGETABLE *table;
1676 MSIQUERY *dbview = NULL;
1677 MSIQUERY *mergeview = NULL;
1678 LPCWSTR name;
1679 UINT r;
1681 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1682 'F','R','O','M',' ','`','%','s','`',0};
1684 name = MSI_RecordGetString(rec, 1);
1686 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1687 if (r != ERROR_SUCCESS)
1688 goto done;
1690 if (TABLE_Exists(data->db, name))
1692 r = MSI_OpenQuery(data->db, &dbview, query, name);
1693 if (r != ERROR_SUCCESS)
1694 goto done;
1696 r = merge_verify_colnames(dbview, mergeview);
1697 if (r != ERROR_SUCCESS)
1698 goto done;
1700 r = merge_verify_primary_keys(data->db, data->merge, name);
1701 if (r != ERROR_SUCCESS)
1702 goto done;
1705 r = msi_get_merge_table(data->merge, name, &table);
1706 if (r != ERROR_SUCCESS)
1707 goto done;
1709 data->curtable = table;
1710 data->curview = mergeview;
1711 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1712 if (r != ERROR_SUCCESS)
1714 free_merge_table(table);
1715 goto done;
1718 list_add_tail(data->tabledata, &table->entry);
1720 done:
1721 msiobj_release(&dbview->hdr);
1722 msiobj_release(&mergeview->hdr);
1723 return r;
1726 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1727 struct list *tabledata)
1729 static const WCHAR query[] = {
1730 'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1731 '`','_','T','a','b','l','e','s','`',0};
1732 MSIQUERY *view;
1733 MERGEDATA data;
1734 UINT r;
1736 r = MSI_DatabaseOpenViewW(merge, query, &view);
1737 if (r != ERROR_SUCCESS)
1738 return r;
1740 data.db = db;
1741 data.merge = merge;
1742 data.tabledata = tabledata;
1743 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1744 msiobj_release(&view->hdr);
1745 return r;
1748 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1750 UINT r;
1751 MERGEROW *row;
1752 MSIVIEW *tv;
1754 if (!TABLE_Exists(db, table->name))
1756 r = msi_add_table_to_db(db, table->columns, table->types,
1757 table->labels, table->numlabels, table->numcolumns);
1758 if (r != ERROR_SUCCESS)
1759 return ERROR_FUNCTION_FAILED;
1762 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1764 r = TABLE_CreateView(db, table->name, &tv);
1765 if (r != ERROR_SUCCESS)
1766 return r;
1768 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1769 tv->ops->delete(tv);
1771 if (r != ERROR_SUCCESS)
1772 return r;
1775 return ERROR_SUCCESS;
1778 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1779 LPWSTR table, DWORD numconflicts)
1781 UINT r;
1782 MSIQUERY *view;
1784 static const WCHAR create[] = {
1785 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1786 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1787 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1788 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1789 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1790 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1791 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1792 static const WCHAR insert[] = {
1793 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1794 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1795 '`','N','u','m','R','o','w','M','e','r','g','e',
1796 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1797 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1799 if (!TABLE_Exists(db, error))
1801 r = MSI_OpenQuery(db, &view, create, error);
1802 if (r != ERROR_SUCCESS)
1803 return r;
1805 r = MSI_ViewExecute(view, NULL);
1806 msiobj_release(&view->hdr);
1807 if (r != ERROR_SUCCESS)
1808 return r;
1811 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1812 if (r != ERROR_SUCCESS)
1813 return r;
1815 r = MSI_ViewExecute(view, NULL);
1816 msiobj_release(&view->hdr);
1817 return r;
1820 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1821 LPCWSTR szTableName)
1823 struct list tabledata = LIST_INIT(tabledata);
1824 struct list *item, *cursor;
1825 MSIDATABASE *db, *merge;
1826 MERGETABLE *table;
1827 BOOL conflicts;
1828 UINT r;
1830 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1831 debugstr_w(szTableName));
1833 if (szTableName && !*szTableName)
1834 return ERROR_INVALID_TABLE;
1836 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1837 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1838 if (!db || !merge)
1840 r = ERROR_INVALID_HANDLE;
1841 goto done;
1844 r = gather_merge_data(db, merge, &tabledata);
1845 if (r != ERROR_SUCCESS)
1846 goto done;
1848 conflicts = FALSE;
1849 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1851 if (table->numconflicts)
1853 conflicts = TRUE;
1855 r = update_merge_errors(db, szTableName, table->name,
1856 table->numconflicts);
1857 if (r != ERROR_SUCCESS)
1858 break;
1860 else
1862 r = merge_table(db, table);
1863 if (r != ERROR_SUCCESS)
1864 break;
1868 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1870 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1871 list_remove(&table->entry);
1872 free_merge_table(table);
1875 if (conflicts)
1876 r = ERROR_FUNCTION_FAILED;
1878 done:
1879 msiobj_release(&db->hdr);
1880 msiobj_release(&merge->hdr);
1881 return r;
1884 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1886 MSIDBSTATE ret = MSIDBSTATE_READ;
1887 MSIDATABASE *db;
1889 TRACE("%d\n", handle);
1891 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1892 if( !db )
1894 IWineMsiRemoteDatabase *remote_database;
1896 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1897 if ( !remote_database )
1898 return MSIDBSTATE_ERROR;
1900 IWineMsiRemoteDatabase_Release( remote_database );
1901 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1903 return MSIDBSTATE_READ;
1906 if (db->mode != MSIDBOPEN_READONLY )
1907 ret = MSIDBSTATE_WRITE;
1908 msiobj_release( &db->hdr );
1910 return ret;
1913 typedef struct _msi_remote_database_impl {
1914 IWineMsiRemoteDatabase IWineMsiRemoteDatabase_iface;
1915 MSIHANDLE database;
1916 LONG refs;
1917 } msi_remote_database_impl;
1919 static inline msi_remote_database_impl *impl_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase *iface )
1921 return CONTAINING_RECORD(iface, msi_remote_database_impl, IWineMsiRemoteDatabase_iface);
1924 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1925 REFIID riid,LPVOID *ppobj)
1927 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1928 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1930 IWineMsiRemoteDatabase_AddRef( iface );
1931 *ppobj = iface;
1932 return S_OK;
1935 return E_NOINTERFACE;
1938 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1940 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1942 return InterlockedIncrement( &This->refs );
1945 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1947 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1948 ULONG r;
1950 r = InterlockedDecrement( &This->refs );
1951 if (r == 0)
1953 MsiCloseHandle( This->database );
1954 msi_free( This );
1956 return r;
1959 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1960 LPCWSTR table, MSICONDITION *persistent )
1962 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1963 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
1964 return S_OK;
1967 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1968 LPCWSTR table, MSIHANDLE *keys )
1970 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1971 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
1972 return HRESULT_FROM_WIN32(r);
1975 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1976 UINT updatecount, MSIHANDLE *suminfo )
1978 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1979 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1980 return HRESULT_FROM_WIN32(r);
1983 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1984 LPCWSTR query, MSIHANDLE *view )
1986 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1987 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
1988 return HRESULT_FROM_WIN32(r);
1991 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1993 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1994 This->database = handle;
1995 return S_OK;
1998 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
2000 mrd_QueryInterface,
2001 mrd_AddRef,
2002 mrd_Release,
2003 mrd_IsTablePersistent,
2004 mrd_GetPrimaryKeys,
2005 mrd_GetSummaryInformation,
2006 mrd_OpenView,
2007 mrd_SetMsiHandle,
2010 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
2012 msi_remote_database_impl *This;
2014 This = msi_alloc( sizeof *This );
2015 if (!This)
2016 return E_OUTOFMEMORY;
2018 This->IWineMsiRemoteDatabase_iface.lpVtbl = &msi_remote_database_vtbl;
2019 This->database = 0;
2020 This->refs = 1;
2022 *ppObj = &This->IWineMsiRemoteDatabase_iface;
2024 return S_OK;